package com.amt.olcacon;

import com.amt.olcacon.utils.DateUtils;
import lombok.Data;
import org.apache.derby.impl.sql.execute.CurrentDatetime;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class PlaceholderTableReplacer {
    
    public static void main(String[] args) throws Exception {
        // 加载模板文件
        InputStream is = new FileInputStream("src/main/resources/templates/LCA报告模板.docx");
        XWPFDocument doc = new XWPFDocument(is);
        
        // 替换占位符表格
        replacePlaceholderTable(doc);
        
        // 保存修改后的文档
        FileOutputStream out = new FileOutputStream("src/main/resources/templates/"+ UUID.randomUUID().toString() +"LCA报告_修改后.docx");
        doc.write(out);
        out.close();
        doc.close();
        
        System.out.println("表格替换完成！");
    }
    
    /**
     * 替换包含占位符的表格
     */
    public static void replacePlaceholderTable(XWPFDocument doc) {
        // 遍历文档中的所有表格
        for (XWPFTable table : doc.getTables()) {
            // 检查表格是否包含占位符
            if (containsPlaceholder(table, "{{ALLOCATION_TABLE}}")) {
                System.out.println("找到占位符表格，开始替换...");
                
                // 生成动态数据
                List<AllocationData> allocationData = generateAllocationData();
                
                // 替换表格内容
                replaceTableContent(table, allocationData);
                break;
            }
        }
    }
    
    /**
     * 检查表格是否包含占位符
     */
    private static boolean containsPlaceholder(XWPFTable table, String placeholder) {
        for (XWPFTableRow row : table.getRows()) {
            for (XWPFTableCell cell : row.getTableCells()) {
                String cellText = cell.getText().trim();
                if (cellText.contains(placeholder)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    /**
     * 替换表格内容
     */
    private static void replaceTableContent(XWPFTable table, List<AllocationData> dataList) {
        // 清空现有表格内容
        clearTableContent(table);
        
        // 设置表格样式
        setupTableStyle(table);
        
        // 创建表头
        createTableHeader(table);
        
        // 填充数据行
        createDataRows(table, dataList);
    }
    
    /**
     * 清空表格内容
     */
    private static void clearTableContent(XWPFTable table) {
        int rowCount = table.getNumberOfRows();
        for (int i = rowCount - 1; i >= 0; i--) {
            table.removeRow(i);
        }
    }
    
    /**
     * 设置表格样式
     */
    private static void setupTableStyle(XWPFTable table) {
        CTTbl ctTable = table.getCTTbl();
        CTTblPr tblPr = ctTable.getTblPr();
        if (tblPr == null) {
            tblPr = ctTable.addNewTblPr();
        }
        
        // 表格宽度设置为100%
        CTTblWidth tblWidth = tblPr.addNewTblW();
        tblWidth.setType(STTblWidth.PCT);
        tblWidth.setW(BigInteger.valueOf(5000)); // 5000 = 100%
        
        // 表格边框
        CTTblBorders borders = tblPr.addNewTblBorders();
        setBorder(borders.addNewBottom(), STBorder.SINGLE, 4, "000000");
        setBorder(borders.addNewTop(), STBorder.SINGLE, 4, "000000");
        setBorder(borders.addNewLeft(), STBorder.SINGLE, 4, "000000");
        setBorder(borders.addNewRight(), STBorder.SINGLE, 4, "000000");
        setBorder(borders.addNewInsideH(), STBorder.SINGLE, 2, "000000");
        setBorder(borders.addNewInsideV(), STBorder.SINGLE, 2, "000000");
    }
    
    private static void setBorder(CTBorder border, STBorder.Enum style, int size, String color) {
        border.setVal(style);
        border.setSz(BigInteger.valueOf(size));
        border.setColor(color);
    }
    
    /**
     * 创建表头
     */
    private static void createTableHeader(XWPFTable table) {
        XWPFTableRow headerRow = table.createRow();
        
        String[] headers = {"序号", "工序名称", "副产品名称", "分配方法", "分配系数", "描述"};
        
        for (int i = 0; i < headers.length; i++) {
            XWPFTableCell cell = headerRow.getCell(i);
            if (cell == null) {
                cell = headerRow.createCell();
            }
            
            // 设置单元格文本和样式
            setCellContent(cell, headers[i], true, true);
        }
        
        // 设置表头行背景色
        setRowBackground(headerRow, "D3D3D3"); // 浅灰色背景
    }
    
    /**
     * 创建数据行
     */
    private static void createDataRows(XWPFTable table, List<AllocationData> dataList) {
        for (int i = 0; i < dataList.size(); i++) {
            AllocationData data = dataList.get(i);
            XWPFTableRow dataRow = table.createRow();
            
            // 填充数据
            setCellContent(dataRow.getCell(0), String.valueOf(i + 1), false, true);
            setCellContent(dataRow.getCell(1), data.getProcessName(), false, false);
            setCellContent(dataRow.getCell(2), data.getByProductName(), false, false);
            setCellContent(dataRow.getCell(3), data.getAllocationMethod(), false, false);
            setCellContent(dataRow.getCell(4), String.format("%.3f", data.getAllocationFactor()), false, true);
            setCellContent(dataRow.getCell(5), data.getDescription(), false, false);
            
            // 交替行背景色
            if (i % 2 == 1) {
                setRowBackground(dataRow, "F5F5F5"); // 浅灰色交替背景
            }
        }
    }
    
    /**
     * 设置单元格内容
     */
    private static void setCellContent(XWPFTableCell cell, String text, boolean isHeader, boolean centerAlign) {
        if (cell == null) return;
        
        // 清空单元格内容
        for (int i = cell.getParagraphs().size() - 1; i >= 0; i--) {
            cell.removeParagraph(i);
        }
        
        // 创建新段落
        XWPFParagraph paragraph = cell.addParagraph();
        
        // 设置段落对齐
        if (centerAlign) {
            paragraph.setAlignment(ParagraphAlignment.CENTER);
        } else {
            paragraph.setAlignment(ParagraphAlignment.LEFT);
        }
        
        // 创建文本运行
        XWPFRun run = paragraph.createRun();
        run.setText(text != null ? text : "");
        run.setFontFamily("宋体");
        
        if (isHeader) {
            run.setBold(true);
            run.setFontSize(10);
        } else {
            run.setFontSize(9);
        }
        
        // 设置单元格垂直对齐
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
    }
    
    /**
     * 设置行背景色
     */
    private static void setRowBackground(XWPFTableRow row, String hexColor) {
        for (XWPFTableCell cell : row.getTableCells()) {
            cell.setColor(hexColor);
        }
    }
    
    /**
     * 生成多产品分配数据
     */
    private static List<AllocationData> generateAllocationData() {
        List<AllocationData> dataList = new ArrayList<>();
        
        // 这里可以从数据库、配置文件或任何数据源获取数据
        dataList.add(new AllocationData(
            "黏合剂生产", 
            "工艺废水", 
            "物理分配法", 
            0.150, 
            "基于副产品与主产品的质量比例进行分配"
        ));
        
        dataList.add(new AllocationData(
            "金属加工", 
            "金属废料", 
            "经济价值法", 
            0.320, 
            "根据副产品市场价值与主产品总价值的比例分配"
        ));
        
        dataList.add(new AllocationData(
            "组件组装", 
            "废包装材料", 
            "系统扩展法", 
            1.000, 
            "采用替代方法，将副产品视为替代产品"
        ));
        
        dataList.add(new AllocationData(
            "原料预处理", 
            "粉尘排放", 
            "物理分配法", 
            0.085, 
            "基于污染物排放量进行环境影响分配"
        ));
        
        dataList.add(new AllocationData(
            "能源生产", 
            "废热", 
            "能量含量法", 
            0.210, 
            "根据能量含量比例进行分配"
        ));
        
        return dataList;
    }
    
    /**
     * 数据实体类
     */
    public static class AllocationData {
        private String processName;
        private String byProductName;
        private String allocationMethod;
        private double allocationFactor;
        private String description;
        
        public AllocationData(String processName, String byProductName, 
                             String allocationMethod, double allocationFactor, String description) {
            this.processName = processName;
            this.byProductName = byProductName;
            this.allocationMethod = allocationMethod;
            this.allocationFactor = allocationFactor;
            this.description = description;
        }
        
        public String getProcessName() { return processName; }
        public String getByProductName() { return byProductName; }
        public String getAllocationMethod() { return allocationMethod; }
        public double getAllocationFactor() { return allocationFactor; }
        public String getDescription() { return description; }
    }
}